import groovy.sql.Sql

println "数据开始初始化"
def script = new File("tool/build-script/batch.sql").text

def scriptArr = script.tokenize(";")
println "读取SQL脚本" + script

// 各个项目请自行修改数据库地址
def host = "jdbc:mysql://127.0.0.1:3306"
def schemaSql = Sql.newInstance(host + "/information_schema", "root", "root", "com.mysql.jdbc.Driver")
def pattern = ~/:(.+)]/

schemaSql.eachRow("SELECT `SCHEMA_NAME` FROM `SCHEMATA`") {
    def result = it.toString()
    // println result
    if (result = ~/d\d+_core/) {
        def matcher = pattern.matcher(result)
        def dbParam = matcher[0][1]
        // println dbParam

        def sql = Sql.newInstance(host + "/" + dbParam + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8", "root", "root", "com.mysql.jdbc.Driver")
        scriptArr.each { scriptItem ->
            scriptItem = scriptItem.replaceAll(/^\s+/, "")
            scriptItem = scriptItem.replaceAll(/\s+$/, "")
            if (scriptItem.size > 0) {
                try {
                    sql.execute(scriptItem)
                    println "执行SQL脚本" + scriptItem + " 长度：" + scriptItem.size()
                } catch(e) {
                    println e
                }
            }
        }
        println "数据库" + dbParam + "执行完成"
    }
}